package net.dgg.robot.task.quartz;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * 契约锁测试类
 *
 * @author tanghom
 */
public class QysUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static  int CONNECTION_TIMEOUT = 20 * 1000;
    private static String qiyuesuoServerUrl="http://118.112.17.4:9082";
    private static String    qiyuesuoAccessToken="hnx4Owfk2T";
    private static String  qiyuesuoAccessSecret="YCbvbuVfkPuYHQakO8qIXsJp3gcKV1";

    public  String post(String url,Map params){
        String resultStr = "";
        Long timestamp = Long.valueOf(System.currentTimeMillis());
        String signature = DggMd5Util.md5Encode(qiyuesuoAccessToken+qiyuesuoAccessSecret+timestamp);

        String urlNameString = qiyuesuoServerUrl+url;
        try {
            // 创建一个http客户端
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建一个PUT请求ENCRYPT_KEY
            HttpPost httpPost = new HttpPost(urlNameString);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                    .setConnectTimeout(CONNECTION_TIMEOUT)
                    .setSocketTimeout(CONNECTION_TIMEOUT)
                    .build();
            httpPost.setConfig(requestConfig);
            // 组装数据放到HttpEntity中发送到服务器
            StringEntity entity = new StringEntity(JsonUtil.obj2Json(params), "UTF-8");
            Header[] headers = {
                    new BasicHeader("Content-type", "application/json")
                    , new BasicHeader("x-qys-signature", signature)
                    , new BasicHeader("x-qys-accesstoken", qiyuesuoAccessToken)
                    , new BasicHeader("x-qys-timestamp", timestamp.toString())
            };
            httpPost.setHeaders(headers);
            httpPost.setEntity(entity);
            // 向服务器发送PUT请求并获取服务器返回的结果
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回的结果可能放到InputStream中。
                InputStream inputStream = response.getEntity().getContent();
                String line = "";
                StringBuffer buffer = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                resultStr = buffer.toString();
                System.out.println(resultStr);

                if (reader != null) {
                    reader.close();
                }
            } else {
                System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }
    public  String get(String url,Map params){
        String resultStr = "";
        Long timestamp = Long.valueOf(System.currentTimeMillis());
        String signature = DggMd5Util.md5Encode(qiyuesuoAccessToken+qiyuesuoAccessSecret+timestamp);

        String urlNameString = qiyuesuoServerUrl+url;
        try {
            urlNameString = urlNameString + "?" + getUrlParamsFromMap(params);
            // 创建一个http客户端
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建一个PUT请求ENCRYPT_KEY
            HttpGet httpGet = new HttpGet(urlNameString);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                    .setConnectTimeout(CONNECTION_TIMEOUT)
                    .setSocketTimeout(CONNECTION_TIMEOUT)
                    .build();
            httpGet.setConfig(requestConfig);
            // 组装数据放到HttpEntity中发送到服务器
            StringEntity entity = new StringEntity(JsonUtil.obj2Json(params), "UTF-8");
            Header[] headers = {
                    new BasicHeader("Content-type", "application/json")
                    , new BasicHeader("x-qys-signature", signature)
                    , new BasicHeader("x-qys-accesstoken", qiyuesuoAccessToken)
                    , new BasicHeader("x-qys-timestamp", timestamp.toString())
            };
            httpGet.setHeaders(headers);
            // 向服务器发送PUT请求并获取服务器返回的结果
            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回的结果可能放到InputStream中。
                InputStream inputStream = response.getEntity().getContent();
                String line = "";
                StringBuffer buffer = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                resultStr = buffer.toString();
                if (reader != null) {
                    reader.close();
                }
            } else {
                System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }
    /**
     * 将map转换成url参数格式: name1=value1&name2=value2
     * @param map
     * @return
     */
    public static String getUrlParamsFromMap(Map<String, Object> map) {
        try {
            if (null != map) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=")
                            .append(URLEncoder.encode(entry.getValue().toString(), "UTF-8")).append("&");
                }
                String content = stringBuilder.toString();
                if (content.endsWith("&")) {
                    content = StringUtils.substringBeforeLast(content, "&");
                }
                return content;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        String userUrl="/contract/finish";
        String userUrl="/userauth/authurl";
//        String userUrl="/user";
        Map params = new HashMap();
//        params.put("contractId","2729240071721492636");
        params.put("mobile","18613236735");
//        params.put("email","");
        params.put("name","汤宏");
        params.put("cardNo","51162219910213461X");
//        params.put("successPage","");
        System.out.println(new QysUtil().post( userUrl ,params));
//        System.out.println(new QysUtil().get( userUrl ,params));
    }

}
